

import {isObject,extend} from "../base/base";

import fetch from "./fetch";

var _req = function (fetchFun, url, config) {

    if (isObject(url)) {
        config = extend(url);
    } else {
        config = extend(config);
        config.url = url;
    }

    var request = extend(config);
    request.headers = config.headers || {};
    request.method = config.method && config.method.toUpperCase() || "GET";

    if (config.contentType) {
        request.headers['Content-Type'] = config.contentType
    }

    if (config.mode) {
        request.mode = config.mode
    }

    // if(config.method.toLowerCase() == 'post'){
    request.body = config.body;
    // }
    //携带cookie
    request.credentials = 'include';

    var fetchWithTimeout = function (url, options, timeout = 10000) {
        return Promise.race([
            fetchFun(url, options),
            new Promise((_, reject) =>
              setTimeout(() => {
                  reject(new Error('timeout'))
              }, timeout)
            )
        ]);
    }
    //发起 http 请求
    return fetchWithTimeout(config.url, request, config.timeout || 10 * 1000).then(async (response) => {

        // var text = await response.text();

        //把返回的响应头转换为对象，以响应头为对象的属性名称，响应头的值为对应属性的值
        var headers = {};
        var headerEntries = response.headers && response.headers.entries()
        var item = undefined;
        while (headerEntries && (item = headerEntries.next())) {
            if (item.done) {
                break;
            }
            headers[item.value[0]] = item.value[1];
        }

        return {
            text: response.text(),
            body: response.body,
            status: response.status,
            statusText: response.statusText,
            headers: headers,
        }
    })

}

export default function () {
    var fetchFun = fetch();
    
    if(fetchFun){
        return _req.call(this, fetchFun, ...arguments)
    }
    //如果没有实现 fetch 函数，则用 ajax 请求，只有 ie 有这个问题
    //下一步，用 ajax 实现 fetch 功能
    return require('./ajax').default.apply(this, arguments)
};
